#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

static pthread_mutex_t mutex;
static int product_number=0;

void * thread_handle(void *arg){
	int loopCount=atoi((char*)arg);
	for(int i=0;i<loopCount;i++){
		pthread_mutex_lock(&mutex);
		printf("生产者： product_number=%d\n",++product_number);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}

int main(int argc,char* argv[]){
	if(argc<2){
		return 1;
	}
	pthread_t thread[argc-1];
	int ret=0;
	int production_number=0;
	int consumption_number=0;
    for(int i=0;i<argc-1;i++){
		production_number+=atoi(argv[i+1]);
		ret=pthread_create(thread+i,NULL,thread_handle,(void *)argv[i+1]);
		if(ret!=0){
			exit(EXIT_FAILURE);
		}
	}
	while(1){
		pthread_mutex_lock(&mutex);
		while(product_number>0){
			printf("消费者：product_number=%d consumption_number=%d\n",--product_number,++consumption_number);
		}
        
		pthread_mutex_unlock(&mutex);
		if(production_number==consumption_number){
			break;
		}
    }
	for(int i=0;i<argc-1;i++){
		pthread_join(thread[i],NULL);
	}
	pthread_mutex_destroy(&mutex);
    return 0;
}
